<?php
namespace app\common\library;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Http\StreamResponse;
use fast\Http;
class Wxmini
{
    private $app;

    public function __construct()
    {
        $options = [
            'app_id'      =>config('weixin.mini_appid'),
            'secret'      => config('weixin.mini_appsecret'),
            'response_type' => 'array',
        ];
        try {
            $this->app = Factory::miniProgram($options);
        } catch (\Exception $e) {
            \think\Log::error('初始化失败：' . $e->getMessage());
        }
    }
    /**
     * 根据 jsCode 获取用户 session 信息
     */
    public function jscode2session($code){        
        return $this->app->auth->session($code);
    }
    /**
     * 微信小程序消息解密
     */
    public function decryptData($session, $iv, $encryptedData){
    	return $this->app->encryptor->decryptData($session, $iv, $encryptedData);
    }
    /**
     * 敏感词验证
     */
    public function checkContent($content){        
        return $this->app->content_security->checkText($content);
    }
    /**
     * 图片验证
     */
    public function checkMedia($filePath){
    	return $this->app->content_security->checkImage($filePath);
    }

    public function decryptUserInfo($post){
        $wxmini=new \app\common\library\Wxmini();
        $return=$wxmini->decryptData($post['session_key'], $post['iv'], $post['encryptedData']);
        return [
            'status'=>true,
            'data'=>[
                'unionid'=>isset($return['unionId'])?$return['unionId']:'',
                'nickname'=>isset($return['nickName'])?$return['nickName']:'',
                'avatar'=>isset($return['avatarUrl'])?$return['avatarUrl']:'',
                'gender'=>isset($return['gender'])?$return['gender']:0,
            ]
        ];
    }
    /**
     * 获取小程序码-B
     */
    public function getUnlimited($scene,$page)
    {

        $response = $this->app->app_code->getUnlimit($scene,['page'=>$page]);
        \think\Log::error($response);
        $resfilename = '';
        if ($response instanceof StreamResponse) {

            $resfilename = $response->getBodyContents();
        }

        return $resfilename;
    }

    public function getAcesstoken(){
        $accessToken = $this->app->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串
        return $token;
    }
    public function decryptPhoneNumber($post){
        $wxmini=new \app\common\library\Wxmini();
        $return=$wxmini->decryptData($post['session_key'], $post['iv'], $post['encryptedData']);
        return [
            'status'=>true,
            'data'=>[
                'mobile'=>isset($return['phoneNumber'])?$return['phoneNumber']:'',
            ]
        ];
    }
}